package com.wuseguang.springcloud.quartz;

import com.wuseguang.springcloud.util.ClazzUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;


@Component
public class JobOperation {

    private Logger logger = LoggerFactory.getLogger(JobOperation.class);

    private final Scheduler scheduler;

    @Autowired
    public JobOperation(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    @SuppressWarnings("unchecked")
    public void add(String name, String school, List<String> cronList) throws Exception {
        Class clazz = ClazzUtil.getClazz(QuartzContants.package_url, name);
        if (null == clazz) {
            throw new ClassNotFoundException("没有这个定时任务");
        }

        //获取这个学校是不是已经创建了这个任务
        JobDetail jobDetail = scheduler.getJobDetail(JobKey.jobKey(name, school));
        //判断学校是不是已经创建任务了
        if(StringUtils.isEmpty(jobDetail)|| jobDetail ==null){
            logger.info("学校为创建此任务，开始创建此任务");
            jobDetail =  JobBuilder.newJob(clazz).withIdentity(name, school) .storeDurably().build();
        }
        //把触发器与任务绑定到调度器中
        scheduler.addJob(jobDetail, true);

        logger.info("准备创建触发器");
        //循环这个所有
        for (int i = 0;i<cronList.size();i++) {
            logger.info("触发器创建中");
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronList.get(i));
            //创建触发器
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity(name, school+"-"+i).forJob(jobDetail).withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(trigger);
        }

    }


    public void remove(String name, String group) throws Exception {
        TriggerKey triggerKey = TriggerKey.triggerKey(name, group);
        //停止触发器
        scheduler.pauseTrigger(triggerKey);
        //移除触发器
        scheduler.unscheduleJob(triggerKey);
        //删除任务
        scheduler.deleteJob(JobKey.jobKey(name, group));
    }

    public void modify(String name, String group,List<String> cronList) throws Exception {
        //修改因为会额外触发一次，所以先做移除再添加
        //移除
        remove(name, group);
        //添加
        add(name, group, cronList);
    }

    public void removeJobs() throws Exception {
        scheduler.pauseAll();
        scheduler.clear();
    }



}
